package com.tbit.uqbike.tergateway.gt06pkg;

import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.Gt06DeEnCoder;
import com.tbit.uqbike.service.db.DbService;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.tergateway.pojo.TerInfo;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-6-27 16:13
 */
public class Login extends CommPkg {
    private static Logger logger = LoggerFactory.getLogger(Login.class);

    @Override
    public void doBusiness() {
        logger.debug(this.toString());
        // 检查离线指令
        TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);

        DbService dbService = TerGatewayMain.getDbService();
        TerInfo terExist = dbService.getTerInfoByMno(this.mno);
        if (terExist == null) {
            terExist = this.getTerInfo();
            dbService.insertTerInfo(terExist);
        }

        if (terTempData.getOfflineOrderFlag()) {
            terTempData.checkOfflineOrder();
        }
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo conn, AProtocol protocol) {
        ByteBuf byteBuf = Gt06DeEnCoder.buildCommRsp(this);
        return byteBuf;
    }

    private TerInfo getTerInfo() {
        TerInfo info = new TerInfo();
        info.setFactoryCode("GT06");
        info.setFunCode("");
        info.setImei(this.mno);
        info.setImsi("");
        info.setJoinTime(new Date());
        info.setMachineNO(this.mno);
        info.setSoftVersion("");
        return info;
    }
}
